<!-- 作品详情页面 -->
<template>
  <view v-if="loading" class="loading-box">加载中...</view>
  <view v-else-if="!work && !loading" class="error-box">作品不存在</view>
  <view v-else-if="work" class="detail-page">
    <!-- 顶部返回栏 -->
    <view class="nav-bar">
      <text class="back-icon" @click="goBack">‹</text>
    </view>

    <!-- 顶部作品图 -->
    <image :src="work.image" class="banner" mode="aspectFill" />

    <!-- 作品核心信息 -->
    <view class="section">
      <!-- 系列名称 -->
      <view class="series">{{ work.series }}</view>

      <!-- 标题 + 状态标签 -->
      <view class="title-row">
        <text class="title">{{ work.name }}</text>
        <text v-if="work.status" :class="['status-badge', work.status]">
          {{ statusText(work.status) }}
        </text>
      </view>

      <!-- 描述（最多两行，可展开） -->
      <view v-if="work.description" class="description" :class="{ expanded: descExpanded }">
        {{ work.description }}
      </view>
      <text v-if="showToggle" class="toggle-btn" @click="toggleDesc">
        {{ descExpanded ? "收起" : "更多" }}
      </text>

      <view class="interaction">
        <text class="like-count" :class="{ active: liked }" @click="toggleLike">{{ likeCount }}</text>
        <text class="comment-count">110</text>
      </view>
    </view>

    <!-- 价格和版号信息 -->
    <view class="section">
      <view class="info-row">
        <text class="label">价格</text>
        <text class="price">￥{{ work.price }}</text>
      </view>
      <view class="info-row">
        <text class="label">版号数量</text>
        <text>{{ editionSummary }}</text>
      </view>
      <view class="info-row">
        <text class="label">铸造时间</text>
        <text>{{ mintedFormatted }}</text>
      </view>
      <view class="info-row">
        <text class="label">链区</text>
        <text>{{ work.chain }}</text>
      </view>
      <view class="info-row">
        <text class="label">Token ID</text>
        <text>{{ work.token_id }}</text>
      </view>
    </view>

    <!-- 交易记录 -->
    <view v-if="work.transactions?.length" class="section">
      <view class="sub-title">交易记录</view>
      <view class="table-head">
        <text class="col type">事件</text>
        <text class="col user">用户</text>
        <text class="col price">价格</text>
        <text class="col date">日期</text>
      </view>
      <view v-for="(t, idx) in work.transactions" :key="idx" class="table-row">
        <text class="col type">{{ t.type }}</text>
        <text class="col user">{{ t.user }}</text>
        <text class="col price">¥{{ t.price }}</text>
        <text class="col date">{{ t.date }}</text>
      </view>
    </view>

    <!-- 属性 -->
    <view v-if="work.attributes?.length" class="section">
      <view class="sub-title">属性</view>
      <view class="attr-list">
        <view v-for="(attr, idx) in work.attributes" :key="idx" class="attr-item">
          <text class="trait">{{ attr.trait }}</text>
          <text class="value">{{ attr.value }}</text>
          <text class="rarity" v-if="attr.rarity">{{ attr.rarity }}</text>
        </view>
      </view>
    </view>

    <!-- 关于Nexity & 交易须知 -->
    <view class="section">
      <view class="sub-title">关于JinPin</view>
      <view class="disclaimer"> JinPin致力于成为进入元宇宙时代的桥梁。 </view>
      <view class="sub-title disclaimer-title">交易须知</view>
      <view class="disclaimer-item">1.所有作品信息由创作者上传，购买前须仔细甄别并自行判断，平台不为创作者的承诺做担保，如果创作者未兑现其承诺，一切与平台无关。</view>
      <view class="disclaimer-item">2.平台坚决反对数字作品炒作，禁止用户进行任何形式的数字作品炒作及私下交易数字作品。</view>
      <view class="disclaimer-item">3.数字作品一经交易不支持退换，不支持7天无理由退款，请谨慎购买。</view>
      <view class="disclaimer-item">4.如因发布数字作品的用户或者作品原创作者侵权或发布危害国家利益、违反社会道德与公序良俗以及其他负面言论或行为或作品存在权利瑕疵或违法违规等</view>
    </view>

    <!-- 底部购买栏 -->
    <view class="footer-bar">
      <view class="fav-box" @click="toggleFav">
        <text :class="['fav-icon', { active: favorite }]">❤</text>
      </view>
      <button class="buy-btn" @click="buyNow">立即购买</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { http } from "@/pages/utils/Http";
import type { WorkDetail, WorkDetailResponse } from "@/pages/utils/request";

const work = ref<WorkDetail | null>(null);

const loading = ref(false);
const favorite = ref(false);

// ===== 点赞状态管理 =====
const liked = ref(false);
const likeCount = ref(0);
const likeLock = ref(false);

onLoad((options: any) => {
  const id = options?.id;
  if (!id) {
    uni.showToast({ title: "缺少作品ID", icon: "none" });
    return;
  }

  // 设置加载状态为true
  loading.value = true;

  const uid = uni.getStorageSync("userId") || 0;
  console.log("localStorage userId =", uid);
  console.log("localStorage 所有内容 =", uni.getStorageInfoSync());
  http
    .get<WorkDetailResponse>(`/api/works/${id}?userId=${uid}`)
    .then((res) => {
      if (res.code === 200) {
        work.value = res.data;
        liked.value = !!(res.data as any).liked;
        likeCount.value = Number(
          (res.data as any).likeCount ?? (res.data as any).like_count ?? 0
        );
        console.log("detail loaded =>", work.value);
      } else {
        uni.showToast({ title: res.message || "加载失败", icon: "none" });
      }
    })
    .catch((e: any) => {
      uni.showToast({ title: e?.message || "加载失败", icon: "none" });
    })
    .finally(() => {
      loading.value = false;
    });
});

const buyNow = () => {
  // TODO: 调用购买接口或跳转支付
  uni.showToast({ title: "购买功能待接入", icon: "none" });
};

const toggleFav = () => {
  favorite.value = !favorite.value;
  uni.showToast({ title: favorite.value ? "已收藏" : "已取消", icon: "none" });
};

const goBack = () => {
  uni.navigateBack();
};

/* ======= 计算格式化日期 ======= */

const pad = (n: number) => (n < 10 ? "0" + n : n);

const mintedFormatted = computed(() => {
  if (!work.value?.minted_time) return "";
  const raw = work.value.minted_time;

  // 如果是 ISO 格式
  if (/T/.test(raw)) {
    const d = new Date(raw);
    const date = `${d.getFullYear()}.${pad(d.getMonth() + 1)}.${pad(
      d.getDate()
    )}`;
    const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(
      d.getSeconds()
    )}`;
    return `${date}  ${time}`;
  }

  // 如果是 "YYYY-MM-DD HH:mm:ss" 或 "YYYY-MM-DD"
  const parts = raw.split(/\s+/);
  const datePart = parts[0].replace(/-/g, ".");
  const timePart = parts[1] || "";
  return timePart ? `${datePart}  ${timePart}` : datePart;
});

/* ======= 版号数量显示 ======= */

const editionSummary = computed(() => {
  if (!work.value) return "";
  return `${work.value.remaining_edition}/${work.value.total_edition}`;
});

/* ======= 作品描述展开 / 状态文本 ======= */

const descExpanded = ref(false);
const toggleDesc = () => {
  descExpanded.value = !descExpanded.value;
};

const showToggle = computed(() => {
  return (work.value?.description?.length || 0) > 60;
});

const statusText = (s: string) => {
  switch (s) {
    case "review":
      return "审核中";
    case "issued":
      return "已发行";
    case "done":
      return "已结束";
    case "hot":
      return "热门";
    default:
      return s;
  }
};

/* ===== 点赞 / 取消点赞 ===== */
const toggleLike = async () => {
  if (!work.value) return;
  if (likeLock.value) return;
  likeLock.value = true;

  const userId = uni.getStorageSync("userId");
  console.log("点赞函数 - 从本地存储获取的 userId:", userId);
  console.log("点赞函数 - userId 类型:", typeof userId);

  if (!userId) {
    uni.showToast({ title: "请先登录", icon: "none" });
    likeLock.value = false;
    return;
  }

  const prevLiked = liked.value;
  liked.value = !prevLiked;
  likeCount.value += liked.value ? 1 : -1;

  try {
    const url = `/api/works/${work.value.id}/${prevLiked ? "unlike" : "like"}`;
    const requestData = { userId: Number(userId) };
    console.log("点赞函数 - 发送请求数据:", requestData);
    console.log("点赞函数 - 请求URL:", url);

    const res = await http.post<any>(url, requestData);
    if (res.code === 200 && typeof res.likeCount !== "undefined") {
      likeCount.value = Number(res.likeCount);
    }
  } catch (e) {
    // 回滚
    liked.value = prevLiked;
    likeCount.value += liked.value ? 1 : -1;
    uni.showToast({ title: "操作失败", icon: "none" });
  } finally {
    setTimeout(() => {
      likeLock.value = false;
    }, 500);
  }
};
</script>

<style scoped lang="scss">
.detail-page {
  background-color: #fff;
  padding-bottom: 120rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.loading-box,
.error-box {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 32rpx;
}

.banner {
  width: 100%;
  height: 500rpx;
  object-fit: cover;
}

.section {
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  margin-bottom: 8rpx;
  color: #333;
}

.series {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.status-badge {
  padding: 4rpx 10rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  margin-left: 12rpx;
  line-height: 1;
  background-color: #eee;
  color: #666;

  &.review {
    background-color: #ff9500;
    color: #fff;
  }

  &.issued {
    background-color: #34c759;
    color: #fff;
  }

  &.done {
    background-color: #8e8e93;
    color: #fff;
  }

  &.hot {
    background-color: #ff3b30;
    color: #fff;
  }
}

.description {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 显示两行 */
  -webkit-box-orient: vertical;

  &.expanded {
    -webkit-line-clamp: unset;
  }
}

.toggle-btn {
  font-size: 26rpx;
  color: #2e6fff;
  margin-bottom: 16rpx;
}

.interaction {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #999;

  .like-count {
    margin-right: 30rpx;
    cursor: pointer;

    &::before {
      content: "♥ ";
    }

    &.active {
      color: #ff3b30;
    }
  }

  .comment-count {
    &::before {
      content: "💬 ";
    }
  }
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  font-size: 28rpx;

  .label {
    color: #666;
  }

  .price {
    color: #ff3b30;
    font-weight: bold;
    margin-left: auto;
    flex: 0;
  }

  .hash {
    word-break: break-all;
    color: #333;
  }
}

.sub-title {
  font-size: 30rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.table-head,
.table-row {
  display: flex;
  font-size: 26rpx;
  padding: 16rpx 0;
}

.table-head {
  font-weight: 600;
  color: #999;
}

.table-row {
  color: #333;
}

.col {
  flex: 1;
  text-align: center;
}

.type {
  flex: 1.2;
}

.user {
  flex: 1.5;
}

.price {
  flex: 1;
}

.date {
  flex: 1.5;
}

.attr-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.attr-item {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  padding: 16rpx 0;
  border-bottom: 1px solid #f2f2f2;

  &:last-child {
    border-bottom: none;
  }

  .trait {
    color: #2e6fff;
  }

  .value {
    color: #333;
    font-weight: 500;
  }

  .rarity {
    color: #666;
  }
}

.disclaimer {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16rpx;
}

.disclaimer-title {
  font-size: 30rpx;
  font-weight: 600;
  margin: 30rpx 0 20rpx;
  color: #333;
}

.disclaimer-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 12rpx;
}

.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  padding: 0 30rpx;
  border-top: 1px solid #f0f0f0;
}

.fav-box {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fav-icon {
  font-size: 44rpx;
  color: #bbb;

  &.active {
    color: #ff3b30;
  }
}

.buy-btn {
  flex: 1;
  height: 80rpx;
  background: #6f76fb;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-left: 20rpx;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  z-index: 10;
  padding-left: 24rpx;
}

.back-icon {
  font-size: 60rpx;
  color: #333;
  line-height: 1;
  font-weight: 100;
}
</style>
